package com.haima.ziliao.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.haima.common.annotation.RepeatSubmit;
import com.haima.common.utils.DateUtils;
import com.haima.common.utils.SecurityUtils;
import com.haima.utils.OrderGen;
import com.haima.utils.WeChatConstant;
import com.haima.utils.WxPayTool;
import com.haima.ziliao.domain.*;
import com.haima.ziliao.service.*;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.haima.common.annotation.Log;
import com.haima.common.core.controller.BaseController;
import com.haima.common.core.domain.AjaxResult;
import com.haima.common.enums.BusinessType;
import com.haima.common.utils.poi.ExcelUtil;
import com.haima.common.core.page.TableDataInfo;

/**
 * 打印订单Controller
 * 
 * @author hima
 * @date 2024-10-21
 */
@RestController
@RequestMapping("/ziliao/dayinorder")
public class PDayinOrderController extends BaseController
{
    @Autowired
    private IPDayinOrderService pDayinOrderService;
    @Autowired
    private IPMyaddrService myaddrService;
    @Autowired
    private IPDayinCarService dayinCarService;
    @Autowired
    private IPOrdersService pordersService;
    @Autowired
    private IPKuaidiconfigService kuaidiconfigService;


    @PostMapping("/dayin")
    @RepeatSubmit
    public AjaxResult dayin(@RequestParam("id") Long id)
    {
        PMyaddr addr = myaddrService.selectPMyaddrById(id);

        PKuaidiconfig kdf = kuaidiconfigService.selectPKuaidiconfigById(1L);

        Long uid = SecurityUtils.getUserId();

        PDayinCar c = new PDayinCar();
        c.setUid(uid);
        c.setStatus(1);
        List<PDayinCar> carlist = dayinCarService.selectPDayinCarList(c);

        Integer fileNum = carlist.size();

        BigDecimal allmoney = new BigDecimal(0);

        for(int i=0;i<carlist.size();i++){
            BigDecimal je = carlist.get(i).getJine();
            allmoney = allmoney.add(je);
        }

        PDayinOrder dyorder = new PDayinOrder();
        dyorder.setJine(allmoney);
        dyorder.setAddr(addr.getAddr());
        dyorder.setAddTime(DateUtils.getNowDate());
        dyorder.setName(addr.getName());
        dyorder.setName(addr.getName());
        dyorder.setPhone(addr.getPhone());
        dyorder.setStatus("1");
        dyorder.setUid(uid);

        dyorder.setFilespath(JSON.toJSONString(carlist));

        pDayinOrderService.insertPDayinOrder(dyorder);

        String openid = SecurityUtils.getUsername();
        POrders order = new POrders();
        order.setUid(uid);
        order.setOrderType("dayin");
        order.setJine(allmoney.toString());
        order.setName("打印服务 （"+fileNum+"）个文件");
        order.setOrderNum(OrderGen.generateOrderNumber());
        order.setAddTime(DateUtils.getNowDate());
        order.setBid(dyorder.getId());
        if("no".equals(kdf.getSfby())){//不包邮
            order.setYunfei(kdf.getYoufei());
        }else if("manbao".equals(kdf.getSfby())&&allmoney.compareTo(kdf.getManyou())<0){//未满额 不包邮
            order.setYunfei(kdf.getYoufei());
        }else {
            order.setYunfei(new BigDecimal("0"));
        }

        order.setStatus("1");
        try {
            pordersService.insertPOrders(order);

            PrepayRequest pre = getPrepayRequest(allmoney, order, openid);
            PrepayWithRequestPaymentResponse response = WxPayTool.prepayWithRequestPayment(pre);
            System.out.println("============================================预支付信息=====================================================");
            System.out.println(JSON.toJSON(response));

            PDayinCar pc = new PDayinCar();
            pc.setUid(SecurityUtils.getUserId());
            pc.setStatus(2);
            dayinCarService.updatePDayinCarAll(pc);

            return AjaxResult.success(response);
        }catch (Exception e) {
            return AjaxResult.error("获取支付信息失败");
        }
    }

    private static PrepayRequest getPrepayRequest(BigDecimal allmoney, POrders order, String openid) {
        PrepayRequest pre = new PrepayRequest();

        BigDecimal all = allmoney.add(order.getYunfei());

        BigDecimal fen = all.multiply(new BigDecimal(100));
        Integer fenres = fen.intValue();


        Amount amount = new Amount();
        amount.setTotal(fenres);
        pre.setAmount(amount);
        pre.setDescription(order.getName());
        pre.setOutTradeNo(order.getOrderNum());
        pre.setNotifyUrl(WeChatConstant.DAYIN_NOTICE_URL);
        Payer payer = new Payer();
        payer.setOpenid(openid);
        pre.setPayer(payer);
        return pre;
    }

    /**
     * 查询打印订单列表
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:list')")
    @GetMapping("/list")
    public TableDataInfo list(PDayinOrder pDayinOrder)
    {
        startPage();
        List<PDayinOrder> list = pDayinOrderService.selectPDayinOrderList(pDayinOrder);
        return getDataTable(list);
    }

    /**
     * 导出打印订单列表
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:export')")
    @Log(title = "打印订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PDayinOrder pDayinOrder)
    {
        List<PDayinOrder> list = pDayinOrderService.selectPDayinOrderList(pDayinOrder);
        ExcelUtil<PDayinOrder> util = new ExcelUtil<PDayinOrder>(PDayinOrder.class);
        util.exportExcel(response, list, "打印订单数据");
    }

    /**
     * 获取打印订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pDayinOrderService.selectPDayinOrderById(id));
    }

    /**
     * 新增打印订单
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:add')")
    @Log(title = "打印订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PDayinOrder pDayinOrder)
    {
        return toAjax(pDayinOrderService.insertPDayinOrder(pDayinOrder));
    }

    /**
     * 修改打印订单
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:edit')")
    @Log(title = "打印订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PDayinOrder pDayinOrder)
    {
        return toAjax(pDayinOrderService.updatePDayinOrder(pDayinOrder));
    }

    /**
     * 删除打印订单
     */
    @PreAuthorize("@ss.hasPermi('ziliao:dayinorder:remove')")
    @Log(title = "打印订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pDayinOrderService.deletePDayinOrderByIds(ids));
    }
}
